package com.hsogoo.study.concurrency;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.junit.Test;

/**
 * Created by za-huangsaigang on 2018/8/29.
 */
public class ConditionTest {

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    @Test
    public void testCondition() {

        ConditionThread ct = new ConditionThread("ct");

        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " start wt");
            ct.start();

            System.out.println(Thread.currentThread().getName() + " block");
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " continue");
        } finally {
            lock.unlock();
        }

    }

    class ConditionThread extends Thread {

        public ConditionThread(String name) {
            super(name);
        }

        public void run() {

            try {
                lock.lock();// 通过重入锁来获取锁
                System.out.println(Thread.currentThread().getName() + " wakeup others");
                condition.signal();   // 唤醒condition所在锁上等待的其他线程
            } finally {
                lock.unlock();
            }
        }
    }

}
